package com.cvte.sunkit.service

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.view.WindowManager
import androidx.core.app.NotificationCompat
import com.cvte.sunkit.R
import com.cvte.sunkit.callback.StopServiceListener
import com.cvte.sunkit.manage.FloatWindowManager
import com.cvte.sunkit.utils.ActivityCollector

/**
 *  @PackageName com.cvte.sunkit.service
 *  @Description  悬浮窗口的实现,只提供一套生命周期，具体的浮窗操作细节由FloatWindowManager管理
 *  @Author lixu
 *  @Data 2023/7/10 16:58
 *  @Version 1.0
 */
@Suppress("DEPRECATION")
class FloatingService : Service(), StopServiceListener {
    private lateinit var mWindowManager: WindowManager

    private lateinit var mFloatWindowManager: FloatWindowManager


    companion object {

        private const val NOTIFICATION_ID = 1
        private const val CHANNEL_ID = "my_channel_id"
        private const val isOpen=false
    }

    @SuppressLint("InflateParams")
    override fun onCreate() {
        super.onCreate()
        val notification = createNotification() // 提高Service的进程优先级
        startForeground(NOTIFICATION_ID, notification) // 将Service设置为前台服务

        ActivityCollector.finishAll()
    }

    private fun createNotification(): Notification {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(CHANNEL_ID, "my channel", NotificationManager.IMPORTANCE_HIGH)
            val notificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
        val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("sunkit")
            .setContentText("前台进程")
            .setSmallIcon(R.drawable.sun)
        return notificationBuilder.build()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        if(!isOpen) {
            val code = intent.getIntExtra("code", -1)
            val data: Intent = intent.getParcelableExtra("data")!!
            mWindowManager = getSystemService(WINDOW_SERVICE) as WindowManager
            mFloatWindowManager = FloatWindowManager(this, mWindowManager, resources,code,data)
            mFloatWindowManager.addView()
            mFloatWindowManager.fetchData()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onStop() {
        mFloatWindowManager.removeView()
        stopSelf()
    }

    override fun onStopFetchDate() {
        mFloatWindowManager.stopFetchData()
    }
}